package com.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpServer
{
    public static void main(String[] args)
    {
        ServerSocket server = null;
        Socket socket = null;
        OutputStream os = null;
        DataOutputStream dout = null;
        InputStream is = null;
        DataInputStream din = null;
        
        try
        {
            server = new ServerSocket(9090);
            System.out.println("Listening on port 9090....");
            socket = server.accept();
            System.out.println("Client connected : " + socket.getInetAddress().getHostAddress());
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            is = socket.getInputStream();
            din = new DataInputStream(is);
            System.out.println("Server => Integer : " + din.readInt());
            System.out.println("Server => Text : " + din.readUTF());
            
            os = socket.getOutputStream();
            dout = new DataOutputStream(os);
            System.out.println("Server : sending response to client");
            dout.writeUTF("This is message from SERVER");
            dout.flush();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                din.close();
                is.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
